package com.roin.learn.activiti.command;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.impl.cmd.GetBpmnModelCmd;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;

import java.io.InputStream;
import java.util.Collections;
import java.util.List;

public class ProcessInstanceDiagramCmd implements Command<InputStream> {
    protected String processInstanceId;
    /**
     * 通过引擎配置实例获得流程图的字体配置信息，避免流程图中文乱码
     */
    protected ProcessEngineConfiguration processEngineConfiguration;

    public ProcessInstanceDiagramCmd(String processInstanceId,ProcessEngineConfiguration processEngineConfiguration) {
        this.processInstanceId = processInstanceId;
        this.processEngineConfiguration = processEngineConfiguration;
    }

    public InputStream execute(CommandContext commandContext) {
        ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
        ExecutionEntity executionEntity = executionEntityManager.findExecutionById(processInstanceId);
        List<String> activiityIds = executionEntity.findActiveActivityIds();
        String processDefinitionId = executionEntity.getProcessDefinitionId();

        GetBpmnModelCmd getBpmnModelCmd = new GetBpmnModelCmd(
                processDefinitionId);
        BpmnModel bpmnModel = getBpmnModelCmd.execute(commandContext);
        InputStream is = new DefaultProcessDiagramGenerator().generateDiagram(bpmnModel,"png", activiityIds,
                Collections.EMPTY_LIST,processEngineConfiguration.getActivityFontName(),processEngineConfiguration.getLabelFontName(),
                processEngineConfiguration.getAnnotationFontName(),processEngineConfiguration.getClassLoader(),1.0);

        return is;
    }
}